package com.telnetnz.ticketdesk.common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import org.apache.log4j.Logger;

import com.telnetnz.ticketdesk.common.config.SpringContext;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class GenericPageMaker {

	private static Logger logger = Logger.getLogger(GenericPageMaker.class);
	/**
	 * 
	 * 
	 * @param templateName  use template.getId()+""
	 * @param filePath full file path which includes File directory + file name, e.g. /var/files/export/2012/11/a9a8sd8d9a9a0a8d0a.xml
	 * @param encoding use mediaFeed.getEncoding
	 * @param data the content map
	 * @return
	 */
	public static boolean process(String templateName, String filePath, String encoding, Map<String, Object> data) 
	{
		Configuration cfg = SpringContext.getFreeMarkerConfiguration();
		Template template;
		try 
		{
			template = cfg.getTemplate(templateName);
		}
		catch (IOException e) 
		{
			logger.info("No such template:" + templateName);
			logger.debug(e.getMessage(), e);
			return false;
		}

		if (template == null || filePath == null || filePath.length() == 0 || filePath.equals("/") || filePath.equals(".")) return false;

		// 去除路径中最前面的'/'
		if ('/' == filePath.charAt(0)) filePath = filePath.substring(1);

		// 提取路径
		String folderPath;
		if (filePath.lastIndexOf('/') > 0)
			folderPath = filePath.substring(0, filePath.lastIndexOf('/'));
		else
			folderPath = "";

		if (!verifyFilePath(folderPath)) 
		{
			logger.info("Create folder " + folderPath + " failed.");
			return false;
		}
		File outputFile = new File(filePath);
		logger.debug("Output File: "+ filePath);
		try 
		{
			Writer writer = new OutputStreamWriter(new FileOutputStream(outputFile), encoding);
			template.process(data, writer);
			writer.flush();
			writer.close();
		} 
		catch (FileNotFoundException e)
		{
			logger.info("File not found :" + filePath);
			logger.debug(e.getMessage(), e);
			return false;
		} 
		catch (TemplateException e) 
		{
			logger.info("Template Exception");
			logger.debug(e.getMessage(), e);
			return false;
		} 
		catch (IOException e) 
		{
			logger.info("I/O Exception");
			logger.debug(e.getMessage(), e);
			return false;
		} 
		catch (Exception e) 
		{
			logger.info("Unknown Exception");
			logger.debug(e.getMessage(), e);
			return false;
		}

		return true;
	}
	
	
	public static String process(String templateName,  String encoding, Map<String, Object> data) 
	{
		Configuration cfg = SpringContext.getFreeMarkerConfiguration();
		Template template;
		String rs = "";
		try 
		{
			template = cfg.getTemplate(templateName);
		} 
		catch (IOException e) 
		{
			logger.info("IOException: " + templateName);
			logger.debug(e.getMessage(), e);
			return null;
		}

		if (template == null )
		{
			logger.info("No such template:" + templateName);
			return null;
		}

		try 
		{
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			Writer writer = new OutputStreamWriter(out, encoding);
			template.process(data, writer);
			writer.flush();
			writer.close();
			byte[] bytes = out.toByteArray();
			rs = new String(bytes, encoding);
		}
		catch (TemplateException e) 
		{
			logger.info("Template Exception");
			logger.debug(e.getMessage(), e);
			return null;
		}
		catch (Exception e) 
		{
			logger.info("Unknown Exception");
			logger.debug(e.getMessage(), e);
			return null;
		}

		return rs;
	}

	
	/**
	 * 检查并生成路径. 如果生成失败则返回false
	 * 
	 * @param absolutePath
	 * @return
	 */
	private static boolean verifyFilePath(String absolutePath) {
		File file = new File(absolutePath);
		if (file.exists()) 
			return true;
		else
			return file.mkdirs();
	}
}
